package com.higgins.law.server;

import java.net.URL;
import java.util.List;

import com.higgins.client.GreetingService;
import com.higgins.client.dataModel.CoveringLetterDTO;
import com.higgins.client.dataModel.LawFirmDTO;
import com.higgins.client.dataModel.RecipientDTO;
import com.higgins.client.dataModel.StrategyDTO;
import com.seguedevelopment.gwtrpccommlayer.client.GwtRpcCommLayerClient;

public class LawAppConnectivity {
	private WordDocumentFactory documentFactory = null;
	private URL url = null;
	private GwtRpcCommLayerClient client = null;
	private GreetingService stub  = null;

	public LawAppConnectivity()	{
		
	}
	public void initialise()	{
		try	{
			url = new URL("http://127.0.0.1:8888/hibernatecloudsql/greet");
			client = new GwtRpcCommLayerClient(url);
			stub = (GreetingService) client.createRemoteServicePojoProxy(GreetingService.class);
		} catch (Exception e)	{
			System.out.println("Something Went Wrong!");
		} finally	{
			System.out.println("DONE");
		}
	}
	public void startPublishing(WordDocumentFactory documentFactory)	{
		this.documentFactory = documentFactory;
		List<StrategyDTO> list = stub.retrieveStrategys();
		for (StrategyDTO strategyDTO:list)		{
			if (strategyDTO.getStatus() == 1)	{
				System.out.println("Get Ready To Publish Strategy: " + strategyDTO.getName());
				publishStrategy(strategyDTO);
			}
		}			
	}
	private void publishStrategy(StrategyDTO strategyDTO)	{
		List<RecipientDTO> recipients = stub.retrieveRecipients(strategyDTO);
		for (RecipientDTO recipientDTO:recipients)	{
			System.out.println(recipientDTO.getName() + "; " + recipientDTO.getAddress());

			String templateFileName = strategyDTO.getName() + ".doc";
			CoveringLetterDTO coveringLetterDTO = strategyDTO.getCoveringLetterDTO();
			String googleId = coveringLetterDTO.getGoogleCode();
			LawFirmDTO lawFirmDTO = recipientDTO.getLawFirmDTO();
			String lawFirm = lawFirmDTO.getName();
			String address = recipientDTO.getAddress();
			String contact = recipientDTO.getName();
			
//			 templateFileName = "Hello.doc";
//			 googleId = "0B_-MLz06YINjM19LM2xON2RCN0E";
//			 lawFirm = "Squire, Sanders";
//			 address = "Tower 42, London, EC4Y";
//			 contact = "Mr. Lewis";
			System.out.println("About to publish...." + templateFileName + ", " + googleId + ", " + lawFirm + ", " + address + ", " + contact);
			documentFactory.createCoveringLetter(templateFileName, googleId, lawFirm, address, contact);
			System.out.println("Publish Complete...." + templateFileName + ", " + googleId + ", " + lawFirm + ", " + address + ", " + contact);
		}
	}	
}
